// --------------------------------------------------------------------------------------------------------------------
// <copyright file="RobotiqSModelVisualizationAgent.cs" company="Microsoft Corporation">
// The MIT License (MIT)
// 
// Copyright (c) 2014, Microsoft Corporation
// 
// Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
// 
// The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
// 
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
// </copyright>
// --------------------------------------------------------------------------------------------------------------------
namespace Microsoft.Robotics.Hardware.Visualization.Robotiq
{
    using System;
    using System.Runtime.Serialization;
    using System.Text;
    using Microsoft.Robotics.Hardware.Robotiq;
    using Microsoft.Robotics.Hardware.Runtime.Robotiq;
    using Microsoft.Robotics.Runtime;
    using Microsoft.Robotics.Visualization;

    /// <summary>
    /// This model agent class prepares visualization for arm manipulation.
    /// </summary>
    [DataContract]
    public sealed class RobotiqSModelVisualizationAgent : ModelAgent<RobotiqSModelStateMessage, RobotiqSModelDisplayModel>
    {
        /// <summary>
        /// Name of the Robotiq S Model agent
        /// </summary>
        [DataMember(Name = "RobotiqAgentName")]
        private string robotiqAgentName = default(string);

        /// <summary>
        /// Control port for robotiq gripper
        /// </summary>
        private IForwarder<RobotiqSModelControlMessage> robotiqControlPort;

        /// <summary>
        /// Current basic command
        /// </summary>
        private RobotiqSModelBasicCommand basicCommand;

        /// <summary>
        /// Initializes a new instance of the <see cref="RobotiqSModelVisualizationAgent" /> class.
        /// </summary>
        /// <param name="name">Agent name</param>
        /// <param name="producer">The name of the agent we subscribe to.</param>
        /// <param name="maxUpdateIntervalMilliseconds">The interval on which to issue data binding updates to the UI</param>
        /// <param name="robotiqAgentName">Robotiq S Model agent name</param>
        public RobotiqSModelVisualizationAgent( 
            string name,
            IProducer<RobotiqSModelStateMessage> producer,
            int maxUpdateIntervalMilliseconds,
            string robotiqAgentName)
            : base(name, producer.Name, maxUpdateIntervalMilliseconds)
        {
            this.robotiqAgentName = robotiqAgentName;
        }

        /// <summary>
        /// Initializes any fields not provided in the manifest.
        /// </summary>
        /// <param name="locator">Not used.</param>
        public override void Initialize(AgentLocator locator)
        {
            base.Initialize(locator);

            if (!string.IsNullOrEmpty(this.robotiqAgentName))
            {
                IAgentHost robotiqAgent = locator.GetAgent(this.robotiqAgentName);
                robotiqAgent.Subscribe<RobotiqSModelStateMessage>(this);
                this.robotiqControlPort = robotiqAgent.GetControlPort<RobotiqSModelControlMessage>();
            }

            this.basicCommand = new RobotiqSModelBasicCommand(
                false,
                RobotiqSModelGripModes.Basic,
                false,
                0,
                0,
                0);
        }

        /// <summary>
        /// Updates the model data with the new state.
        /// </summary>
        /// <param name="message">The new state from the upstream agent.</param>
        /// <returns>true if the model was updated, false otherwise</returns>
        protected override bool UpdateModel(RobotiqSModelStateMessage message)
        {
            RobotiqSModelState state = message.State;
            if (state.Fault != RobotiqSModelFaults.NoFault)
            {
                this.Model.ActivationStatus = state.Fault.ToString();
            }

            if (state.IsActivated)
            {
                this.Model.ActivationStatus = "Activated";
            }
            else
            {
                this.Model.ActivationStatus = "Not Activated";
            }

            this.Model.GripMode = state.GripMode.ToString();

            this.Model.GripperStatus = state.DeviceStatus.ToString();

            this.Model.GripStatus = state.GripStatus.ToString();

            if (state.GoToPosition)
            {
                this.Model.GoToPosition = "true";
            }
            else
            {
                this.Model.GoToPosition = "false";
            }

            this.Model.CommandedPosition = state.FingerAState.CommandedPosition.ToString();

            this.Model.FingerAPositionString = state.FingerAState.Position.ToString() + " counts";
            this.Model.FingerBPositionString = state.FingerBState.Position.ToString() + " counts";
            this.Model.FingerCPositionString = state.FingerCState.Position.ToString() + " counts";
            this.Model.ScissorAxisPositionString = state.ScissorState.Position.ToString() + " counts";

            this.Model.FingerACurrentString = state.FingerAState.CurrentInMilliAmps.ToString() + " mA";
            this.Model.FingerBCurrentString = state.FingerBState.CurrentInMilliAmps.ToString() + " mA";
            this.Model.FingerCCurrentString = state.FingerCState.CurrentInMilliAmps.ToString() + " mA";
            this.Model.ScissorAxisCurrentString = state.ScissorState.CurrentInMilliAmps.ToString() + " mA";

            this.Model.FingerAStatusString = state.FingerAState.FingerStatus.ToString();
            this.Model.FingerBStatusString = state.FingerBState.FingerStatus.ToString();
            this.Model.FingerCStatusString = state.FingerCState.FingerStatus.ToString();
            this.Model.ScissorAxisStatusString = state.ScissorState.FingerStatus.ToString();

            if (this.Model.DoActivate)
            {
                RobotiqSModelControlMessage gripperMessage = new RobotiqSModelControlMessage(
                    message.OriginatingTime,
                    new RobotiqSModelBasicCommand(
                        true,
                        RobotiqSModelGripModes.Basic,
                        false,
                        0,
                        0,
                        0),
                        true);

                this.robotiqControlPort.Post(gripperMessage);

                this.basicCommand.Activate = true;

                this.Model.DoActivate = false;
            }

            if (this.Model.DoDeactivate)
            {
                RobotiqSModelControlMessage gripperMessage = new RobotiqSModelControlMessage(
                                message.OriginatingTime,
                                new RobotiqSModelBasicCommand(
                                    false,
                                    RobotiqSModelGripModes.Basic,
                                    false,
                                    0,
                                    0,
                                    0),
                                    true);

                this.robotiqControlPort.Post(gripperMessage);

                this.basicCommand.Activate = false;

                this.Model.DoDeactivate = false;
            }

            if (this.Model.SetBasicMode)
            {
                this.basicCommand.GripMode = RobotiqSModelGripModes.Basic;
                this.Model.SetBasicMode = false;
            }
            else if (this.Model.SetPinchMode)
            {
                this.basicCommand.GripMode = RobotiqSModelGripModes.Pinch;
                this.Model.SetPinchMode = false;
            }
            else if (this.Model.SetWideMode)
            {
                this.basicCommand.GripMode = RobotiqSModelGripModes.Wide;
                this.Model.SetWideMode = false;
            }
            else if (this.Model.SetScissorMode)
            {
                this.basicCommand.GripMode = RobotiqSModelGripModes.Scissor;
                this.Model.SetScissorMode = false;
            }

            this.basicCommand.GoToPosition = this.Model.GoToPositionCommand;

            this.basicCommand.Position = this.Model.PositionCommand;

            this.basicCommand.Speed = this.Model.SpeedCommand;

            this.basicCommand.Force = this.Model.ForceCommand;

            this.robotiqControlPort.Post(
                new RobotiqSModelControlMessage(
                    message.OriginatingTime,
                    this.basicCommand,
                    false));

                this.Model.SetCommand = false;

            return true;
        }
    }
}
